//
//  MHNearByHomeCollectionViewController.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/10/10.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHNearByHomeCollectionViewController.h"
#import "MHHomeDiscoverItemCollectionViewCell.h"
#import "MHDiscoverHomeViewModel.h"
#import "MHNearByHomeHeaderView.h"
#import "MHNearByHomeTableViewModel.h"
#import "MHNearCollectionViewModel.h"
#import "MHLocationManager.h"
#import "MHNearByModel.h"
#import "MHWebViewModel.h"
#import "UIScrollView+MHRefresh.h"
#import <SDWebImage/SDImageCacheConfig.h>
@interface MHNearByHomeCollectionViewController ()<MHLocationManagerAppdelegate>
@property (nonatomic, readwrite, strong) MHNearByHomeTableViewModel *viewModel;
@property(nonatomic, assign) BOOL authorizationAccess;
@property(nonatomic, strong) NSArray *circleData;
@property(nonatomic, assign) CLAuthorizationStatus status;
@end

@implementation MHNearByHomeCollectionViewController

@dynamic viewModel;
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.collectionView mh_registerNibCell:MHHomeDiscoverItemCollectionViewCell.class];
    self.collectionView.backgroundColor = MHColorFromHexString(@"#F8F8F8");
    self.authorizationAccess = [MHLocationManager isLocationServiceOpen];
    [self.collectionView registerClass:[MHNearByHomeHeaderView class] forSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:@"DiscoverHeaderView"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:CHTCollectionElementKindSectionFooter withReuseIdentifier:@"FooterView"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
    
    
    if (self.viewModel.shouldPullDownToRefresh) {
        /// 下拉刷新
        @weakify(self);
        [self.collectionView mh_addHeaderRefresh:^(MJRefreshNormalHeader *header) {
            /// 加载下拉刷新的数据
            @strongify(self);
            [self tableViewDidTriggerHeaderRefresh];
        }];
        if (!self.authorizationAccess) {

            [self.collectionView.mj_header endRefreshing];
            
            return;
        }
        [self.collectionView.mj_header beginRefreshing];
    }
    
//    [[MHLocationManager sharedInstance] startUpdatingLocationWithBlock:^(id location) {
//
//    }];
    
    @weakify(self);
    [[MHNotificationCenter rac_addObserverForName:MHReloadDiscoverHomeCircleDataNotification object:nil] subscribeNext:^(NSNotification *note) {
        @strongify(self);
        [self.viewModel.requestRemoteDataCommand execute:@1];
    }];
    
    [[MHNotificationCenter rac_addObserverForName:MHUpdateCurrentLocationNotification object:nil] subscribeNext:^(NSNotification *note) {
        @strongify(self);
        [self resetData];
    }];
    
    [RACObserve(self, authorizationAccess) subscribeNext:^(NSNumber *authorization) {
        @strongify(self);
        self.collectionView.mj_header.hidden = ![authorization boolValue];
        
    }];
    [MHLocationManager sharedInstance].delegate = self;
//    [self.locationManager startUpdatingLocation];
}
-(void) resetData
{
    if (!self.authorizationAccess) {
        [self.collectionView.mj_header endRefreshing];
        return;
    }
    [self.collectionView.mj_header beginRefreshing];
    [self tableViewDidTriggerHeaderRefresh];
}
- (void)tableViewDidTriggerHeaderRefresh{
    
     @weakify(self)
    [[MHLocationManager sharedInstance] startUpdatingLocationWithBlock:^(CLLocation *location) {

        @strongify(self);
        self.viewModel.location = location;
        [[[[MHHTTPService sharedInstance] getNearbyCirclePagedListWithLocationLat:location.coordinate.latitude locationLon:location.coordinate.longitude pageNum:1 pageSize:8] mh_parsedResults] subscribeNext:^(NSArray *cireles) {
            self.circleData = cireles;
            @weakify(self);
            [[[self.viewModel.requestRemoteDataCommand
               execute:@1]
              deliverOnMainThread]
             subscribeNext:^(id x) {
                 @strongify(self)
                 self.viewModel.page = 1;
                 /// 重置没有更多的状态
                 if (self.viewModel.shouldEndRefreshingWithNoMoreData) {
                     [self.collectionView.mj_footer resetNoMoreData];
                 }
             } error:^(NSError *error) {
                 @strongify(self)
                 /// 已经在bindViewModel中添加了对viewModel.dataSource的变化的监听来刷新数据,所以reload = NO即可
                 [self.collectionView.mj_header endRefreshing];
             } completed:^{
                 @strongify(self)
                 /// 已经在bindViewModel中添加了对viewModel.dataSource的变化的监听来刷新数据,所以只要结束刷新即可
                 [self.collectionView.mj_header endRefreshing];
                 /// 请求完成
                 
             }];
            
        }];
    }];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [SDImageCache sharedImageCache].config.shouldDecompressImages = NO ;
//    [[SDWebImageDownloader sharedDownloader] setShouldDecompressImages:NO];
//    [[SDWebImageDownloader sharedDownloader] setMaxConcurrentDownloads:1];
//    SDWebImageDownloaderOptions
//    SDImageCacheConfig *config = [SDImageCache sharedImageCache].config;
//    SDImageCache *canche = [SDImageCache sharedImageCache];
////    config.shouldDecompressImages
////    config
//    SDImageCacheOldShouldDecompressImages = config.shouldDecompressImages;
//    config.sho = NO;
    
//
//    SDWebImageDownloader *downloder = [SDWebImageDownloader sharedDownloader];
//    SDImagedownloderOldShouldDecompressImages = downloder.shouldDecompressImages;
//    downloder.shouldDecompressImages = NO;

}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    [SDImageCache sharedImageCache].config.shouldDecompressImages = YES ;
//    [[SDWebImageDownloader sharedDownloader] setShouldDecompressImages:YES];
}


//-(void)dealloc {
//    SDImageCache *canche = [SDImageCache sharedImageCache];
//    canche.shouldDecompressImages = SDImageCacheOldShouldDecompressImages;
//
//    SDWebImageDownloader *downloder = [SDWebImageDownloader sharedDownloader];
//    downloder.shouldDecompressImages = SDImagedownloderOldShouldDecompressImages;
//
//}

-(void)configurelayout:(CHTCollectionViewWaterfallLayout *)layout
{
    layout.headerHeight = 220;
    layout.minimumColumnSpacing = 0;
    layout.minimumInteritemSpacing = 10;
    layout.columnCount = 2;
}





- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{

    UICollectionReusableView *supplementaryView;

    if ([kind isEqualToString:CHTCollectionElementKindSectionHeader]){
        
        if(self.circleData.count <= 0)
        {
            UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
            
            supplementaryView = headerView;
            return supplementaryView;

        }
        MHNearByHomeHeaderView *view = (MHNearByHomeHeaderView *)[collectionView dequeueReusableSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:@"DiscoverHeaderView" forIndexPath:indexPath];
        __weak __typeof(self)weakSelf = self;
        
        view.didselecBlock = ^(MHNearByModel *nearBy){
            MHDiscoverHomeModel *model = [MHDiscoverHomeModel new];
            model.circleId = nearBy.circleId;
            model.isInCircle = nearBy.isInCircle;
            model.circleName = nearBy.title;
            model.payType = nearBy.payType;
            model.circleCode = nearBy.circleCode;
            [AXAppDelegate sharedDelegate].currentDiscoverModel = model;
            if (model.isInCircle) {
//                MLCircleInfoMainPageViewModel *viewModel = [[MLCircleInfoMainPageViewModel alloc] initWithServices:weakSelf.viewModel.services params:@{MHViewModelIDKey:@(model.circleId)}];
//                [weakSelf.viewModel.services pushViewModel:viewModel animated:YES];
                
                [MHMomentHelper redirectToGroupChatWithCircleId:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleId service:self.viewModel.services groupId:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleCode title:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleName];
            }else
            {
                NSString *detailUrl =  [NSString stringWithFormat:@"%@join-circle-app.html?circleId=",[MHConfigureManager h5BaseUrl]];
                NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"%@%ld&userId=%d",detailUrl,(long)nearBy.circleId,[MHHTTPService sharedInstance].currentUser.userId]];
                NSURLRequest *request = [NSURLRequest requestWithURL:url];
                MHWebViewModel * webViewModel = [[MHWebViewModel alloc] initWithServices:weakSelf.viewModel.services params:@{MHViewModelRequestKey:request}];
                webViewModel.showBottomButton = YES;
                [weakSelf.viewModel.services pushViewModel:webViewModel animated:YES];
            }
        };
        [view.moreBtn bk_whenTapped:^{
            MHNearCollectionViewModel *nearBy = [[MHNearCollectionViewModel alloc] initWithServices:weakSelf.viewModel.services params:nil];
            [weakSelf.viewModel.services pushViewModel:nearBy animated:YES];
        }];
        
        view.datas = self.circleData;
        supplementaryView = view;
    }else
    {
        UICollectionReusableView *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:CHTCollectionElementKindSectionFooter withReuseIdentifier:@"FooterView" forIndexPath:indexPath];

        supplementaryView = footerview;
    }
    return supplementaryView;
}


-(void)mhmapLocationManager:(AMapLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    
    if(status == kCLAuthorizationStatusNotDetermined || status == kCLAuthorizationStatusRestricted || status == kCLAuthorizationStatusDenied)
    {
        self.authorizationAccess = NO;
         self.circleData = nil;
        self.viewModel.dataSource = nil;
//        self.collectionView.h
       
        self.viewModel.shouldPullDownToRefresh = NO;
        self.collectionView.mj_header.hidden = YES;
//        [self.collectionView reloadData];
    }else
    {
        
        if (self.status != status) {
            self.authorizationAccess = YES;
            self.viewModel.shouldPullDownToRefresh = YES;
            self.collectionView.mj_header.hidden = NO;
//            __weak __typeof(self)weakSelf = self;
            [self tableViewDidTriggerHeaderRefresh];
            
//            [[MHLocationManager sharedInstance] startUpdatingLocationWithBlock:^(CLLocation *location) {
//                weakSelf.viewModel.location = location;
//                [[[[MHHTTPService sharedInstance] getNearbyCirclePagedListWithLocationLat:location.coordinate.latitude locationLon:location.coordinate.longitude pageNum:1 pageSize:8] mh_parsedResults] subscribeNext:^(NSArray *cireles) {
//                    weakSelf.circleData = cireles;
//                    [weakSelf.viewModel.requestRemoteDataCommand execute:@1];
//                }];
//            }];
        }
    }
    self.status = status;
//
}



- (UICollectionViewCell *)collectionView:(MHCollectionView *)collectionView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
{
    MHHomeDiscoverItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(MHHomeDiscoverItemCollectionViewCell.class) forIndexPath:indexPath];
//
    cell.attriAcountBtn.hidden = self.viewModel.showLoacation;
    cell.broserBtn.hidden = self.viewModel.showLoacation;
    return cell;
}

- (UIEdgeInsets)contentInset{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (void)configureCell:(MHHomeDiscoverItemCollectionViewCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object
{
    [cell bindViewModel:object];
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
//    MHHomeDiscoverItemViewModel *itemViewModel =  self.viewModel.dataSource[indexPath.item];
    return CGSizeMake(MH_SCREEN_WIDTH/2, 310);
}


- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return [UIImage imageNamed:self.authorizationAccess ?  @"globle_emptyData":@"img_found_location" ];
}


- (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
{
    return [UIColor whiteColor];
}


- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = self.authorizationAccess ? @"暂无附近数据" : @"需要开启定位才能使用附近功能~";
    
    NSDictionary *attributes = @{NSFontAttributeName: MHRegularFont_15,
                                 NSForegroundColorAttributeName: MHMetionTextColor};
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}


- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
{
    if (!self.authorizationAccess) {
        NSString *text = nil;
        UIFont *font = nil;
        UIColor *textColor = nil;
        text = @"开启定位";
        font = MHRegularFont_13;
        textColor = MHColorFromHexString(@"#FE1126");
        NSMutableDictionary *attributes = [NSMutableDictionary new];
        if (font) [attributes setObject:font forKey:NSFontAttributeName];
        if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
        return [[NSAttributedString alloc] initWithString:text attributes:attributes];
    }else
    {
        return nil;
    }
    
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button
{
    [[MHLocationManager sharedInstance] openLocationSetting];
}


- (UIImage *)buttonBackgroundImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
{
    if (!self.authorizationAccess) {
        UIEdgeInsets capInsets = UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0);
        UIEdgeInsets rectInsets = UIEdgeInsetsZero;
        capInsets = UIEdgeInsetsMake(25.0, 25.0, 25.0, 25.0);
        rectInsets = UIEdgeInsetsMake(0.0, -100, 0.0, -100);
        
        UIImage *image =    [[[UIImage imageNamed:@"btn_circle_openposition"] resizableImageWithCapInsets:capInsets resizingMode:UIImageResizingModeStretch] imageWithAlignmentRectInsets:rectInsets];
        return  image;
    }else
    {
        return nil;
    }
}




- (CAAnimation *)imageAnimationForEmptyDataSet:(UIScrollView *)scrollView
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath: @"transform"];
    
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    animation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(M_PI_2, 0.0, 0.0, 1.0)];
    
    animation.duration = 0.25;
    animation.cumulative = YES;
    animation.repeatCount = MAXFLOAT;
    
    return animation;
}

@end
